package com.kunminx.architecture.base;

import com.kunminx.core.bus.IResponse;
import com.kunminx.core.bus.Result;
import ohos.aafwk.ability.AbilitySlice;

import java.util.ArrayList;
import java.util.List;

/**
 * @author KunMinX
 * Create at 2018/7/5
 */

public abstract class BaseBusSlice extends AbilitySlice implements IResponse {

    private boolean mIsSliceAnimationEnd = false;

    /**
     * for saving temp init data.
     */
    private List<Result> mInitResult = new ArrayList<>();

    /**
     * for forbidden repeated click in one times
     */
    private long enableTime = 0;

    /**
     * exit time, to judge if is sure to exit
     */
    private long exitTime = 0;

    /**
     * onStop
     *
     */
    @Override
    public void onStop() {
        super.onStop();
        mIsSliceAnimationEnd = false;
    }

    /**
     * load animation success. and then load init data
     *
     */
    @Override
    public void onActive() {  // 不确定
        super.onActive();
        loadInitData();
        mIsSliceAnimationEnd = true;
    }

    private void loadInitData() {
        if (mInitResult.size() > 0) {
            for (int i = 0; i < mInitResult.size(); i++) {
                onResultHandle(mInitResult.get(i));
            }
            mInitResult.clear();
        }
    }

    /**
     * if init animation not loaded, save init data into temp list instead of handle immediately.
     * in order to smoothly load init data instead of blunt.
     *
     * @param testResult
     */
    @Override
    public final void onResult(Result testResult) {
        if (!mIsSliceAnimationEnd && testResult != null) {
            mInitResult.add(testResult);
            return;
        }
        onResultHandle(testResult);
    }

    /**
     * handle result
     *
     * @param testResult
     */
    public abstract void onResultHandle(Result testResult);

    /**
     * for forbidden repeated click in one times
     *
     * @param duration duration for sure
     * @return isEnableToClick
     */
    protected boolean isEnableToClick(long duration) {
        long currentTime = System.currentTimeMillis();
        if (currentTime - enableTime > duration) {
            enableTime = currentTime;
            return true;
        } else {
            return false;
        }
    }

}
